package com.iad.service;

import java.util.List;
import java.util.Map;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.ServletContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.iad.util.Mail;
import com.iad.entity.*;
import com.iad.persistence.SiteDAO;
import com.iad.core.Core;

public class SiteService {
  private ServletContext context;
  private WebApplicationContext wac;
  private SiteDAO siteDAO;
  
	private static Log theLog = LogFactory.getLog(SiteService.class);
  
  /**
   * Default Constructor
   */
  public SiteService(){
      context = flex.messaging.FlexContext.getServletContext();
      wac = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
      siteDAO = (SiteDAO) wac.getBean("siteDAO");
      Core.setServletContext(context);
      Core.setLogger(theLog);
      Log log = Core.getLogger();
      // mail params
      Core.setAdminUser(context.getInitParameter("adminUser"));
      Core.setAdminPassword(context.getInitParameter("adminPassword"));
      Core.setMailServer(context.getInitParameter("mailServer"));
      Core.setMailAuthenticationUser(context.getInitParameter("mailAuthenticationUser"));
      Core.setMailAuthenticationPassword(context.getInitParameter("mailAuthenticationPassword"));
      Core.setEmailTestRecipients(context.getInitParameter("emailTestRecipients"));
      Core.setErrorNotificationRecipients(context.getInitParameter("errorNotificationRecipients"));
  }
  
  
  public Site doLogin(String pathLabel, String password) throws Exception {
    if (Core.getAdminUser().equals(pathLabel) && Core.getAdminPassword().equals(password)) {
      return new Site(-1L, pathLabel, password, true);        
    }
    return siteDAO.findUser(pathLabel, password);
  }
  
  public Site getSite(Long id) throws Exception {
    Site site = siteDAO.find(id);
    site.setPlaylists(siteDAO.getSitePlaylists(id));
    site.setReviews(siteDAO.getSiteReviews(id));
    site.setVideos(siteDAO.getSiteVideos(id));
    System.out.println("SITE: " + site.getName() + " videos: " + site.getVideos().size() + 
                              " playlists: " + site.getPlaylists().size() +
                              " reviews: " + site.getReviews().size() );
    return site;
  }
  
  public Site getSiteByLabel(String label) throws Exception {
    Site site = siteDAO.find(label);
    site.setPlaylists(siteDAO.getSitePlaylists(site.getId()));
    site.setReviews(siteDAO.getSiteReviews(site.getId()));
    site.setVideos(siteDAO.getSiteVideos(site.getId()));
    System.out.println("SITE: " + site.getName() + " videos: " + site.getVideos().size() + 
                              " playlists: " + site.getPlaylists().size() +
                              " reviews: " + site.getReviews().size() );
    return site;
  }
  
  public Long submitReview(Review review) throws Exception {
    String email = "independentartistsdirect@gmail.com";
    Long id = siteDAO.newReview(review);
    Mail.mailNewReviewNotification(email,
        "\"IAD Reviews\" <support@independentartistsdirect.com>",
        "New Review Posted for " + review.getSiteName(),
        "text/html", review);
    return id;
  }

  
  public Site newSite(Site site) throws Exception {
    Long newId = siteDAO.newSite(site);
    // make new directory structure for site
    String tempSiteDir = context.getInitParameter("uploadPath") + "site/sites/0";
    String newSiteDir = context.getInitParameter("uploadPath") + "site/sites/" + newId;
    new File(newSiteDir).mkdir();
    new File(newSiteDir + "/audio").mkdir();
    new File(newSiteDir + "/video").mkdir();
    new File(newSiteDir + "/images").mkdir();
    
    // move icon over to new location
    new File(tempSiteDir + "/images/" + site.getImagePath()).renameTo(new File(newSiteDir + "/images/" + site.getImagePath()));
    
    return getSite(newId);
  }
  
  
  public Long newPlaylist(Playlist playlist) throws Exception {
    Long newId = siteDAO.newPlaylist(playlist);
    return newId;
  }
  
  
  public Long newVideo(Video video) throws Exception {
    Long newId = siteDAO.newVideo(video);
    String tempSiteDir = context.getInitParameter("uploadPath") + "assets/images/";
    String newSiteDir = context.getInitParameter("uploadPath") + "site/sites/" + video.getSiteId();
    // copy temp image over to new location
    System.out.println("Copying " + tempSiteDir + video.getImagePath() + " over to " + newSiteDir + "/images/" + video.getImagePath());
    
    File inputFile = new File(tempSiteDir + video.getImagePath());
    File outputFile = new File(newSiteDir + "/images/" + video.getImagePath());

    FileReader in = new FileReader(inputFile);
    FileWriter out = new FileWriter(outputFile);
    int c;

    while ((c = in.read()) != -1) {
      out.write(c);
    }

    in.close();
    out.close();
    
    return newId;
  }
  
  public void updateSite(Long id, String fileName) throws Exception {
    siteDAO.updateSite(id, fileName);
  }
  
  public void updateSiteProfile(Long id, Map data) throws Exception {
    siteDAO.updateSiteProfile(id, data);
  }
  
  public void updateSiteImage(Long id, String fileName) throws Exception {
    siteDAO.updateSiteImage(id, fileName);
  }
  
  public void updateVideo(Long id, String fileName) throws Exception {
    siteDAO.updateVideo(id, fileName);
  }
  
  public void updatePlaylist(Long id, String fileName) throws Exception {
    siteDAO.updatePlaylist(id, fileName);
  }
  
  public void updatePlaylistDetails(Long siteId, String fileName, String playlistName) throws Exception {
    siteDAO.updatePlaylistDetails(siteId, fileName, playlistName);
  }

  public List getSites() throws Exception {
    return siteDAO.find();
  }
  
  public Playlist getPlaylistFromNewSite(Long siteId) throws Exception {
    return siteDAO.getPlaylistFromNewSite(siteId);
  }
  
  public List getReviews(Long siteId) throws Exception {
    return siteDAO.getReviews(siteId);
  }
  
  public List getNewReviews(Long siteId) throws Exception {
    return siteDAO.getNewReviews(siteId);
  }
  
  public List approveNewReviews(Long siteId, List rejectedReviewIds) throws Exception {
    return siteDAO.approveNewReviews(siteId, rejectedReviewIds);
  }
  
  public Long newSong(Song song) throws Exception {
    return siteDAO.newSong(song);
  }
  
  
  public List getPages(Long siteId) throws Exception {
    return siteDAO.getPages(siteId);
  }
  
  public void updatePage(Page page) throws Exception {
    siteDAO.updatePage(page);
  }
  
  public void updatePages(List pages) throws Exception {
    siteDAO.updatePages(pages);
  }
  
  public void addSongToPlaylist(Song song, Long playlistId) throws Exception {
    siteDAO.addSongToPlaylist(song, playlistId);
  }
  
  public List getSongsInPlaylist(Long playlistId) throws Exception {
    return siteDAO.getSongsInPlaylist(playlistId);
  }
  
  public List getSitePlaylists(Long siteId) throws Exception {
    return siteDAO.getSitePlaylists(siteId);
  }
  
  public List getSiteVideos(Long siteId) throws Exception {
    return siteDAO.getSiteVideos(siteId);
  }
  
  public Long deleteSong(Long id) throws Exception {
    Long retval = siteDAO.deleteSong(id);
    System.out.println("SiteService::deleteSong() returning: " + retval);
    return retval; 
  }
}
